// position_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:stock_helper/modules/position/pages/position_list_item.dart';
import 'dart:async';

import '../controllers/position_controller.dart';


class PositionPage extends StatefulWidget {
  const PositionPage({Key? key}) : super(key: key);

  @override
  _PositionPageState createState() => _PositionPageState();
}

class _PositionPageState extends State<PositionPage> {
  final PositionController controller = Get.put(PositionController());
  final TextEditingController _searchController = TextEditingController();
  final TextEditingController _filterController = TextEditingController(text: '3'); // Set default value to 3
  var _isRefreshing = false.obs;
  Timer? _refreshTimer;
  var _refreshTrigger = 0.obs;

  // 添加可见项跟踪相关变量
  final Map<String, GlobalKey> _itemKeys = <String, GlobalKey>{};
  final GlobalKey _listViewKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    // Apply the default filter (3%) on initial load
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _applyFilter();
    });
    _searchController.addListener(_onSearchChanged);

    // 启动自动刷新检查
    _startAutoRefreshCheck();
  }

  @override
  void dispose() {
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    _filterController.dispose();
    _stopAutoRefreshCheck();
    super.dispose();
  }

  void _onSearchChanged() {
    controller.setSearchQuery(_searchController.text);
  }

  void _applyFilter() {
    final text = _filterController.text;
    if (text.isNotEmpty) {
      final value = double.tryParse(text);
      if (value != null) {
        controller.setFilterPercent(value);
      }
    } else {
      controller.setFilterPercent(0.0);
    }
  }

  void _clearFilter() {
    _filterController.text = ''; // Reset to default value 3
    controller.setFilterPercent(0.0); // Apply default filter
  }

  void _clearSearch() {
    _searchController.clear();
    controller.setSearchQuery('');
  }

  // 启动自动刷新检查
  void _startAutoRefreshCheck() {
    _refreshTimer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (_isTradingTime()) {
        _refreshVisibleStocks();
      }
    });
  }

  // 停止自动刷新检查
  void _stopAutoRefreshCheck() {
    _refreshTimer?.cancel();
    _refreshTimer = null;
  }

  // 判断是否为交易日
  bool _isTradingDay() {
    final now = DateTime.now();
   /* if (now.weekday == DateTime.saturday || now.weekday == DateTime.sunday) {
      return false;
    }*/
    return true;
  }

  // 判断是否在交易时段内
  bool _isTradingTime() {
    if (!_isTradingDay()) return false;

    final now = DateTime.now();
    final time = TimeOfDay.fromDateTime(now);

    final morningStart = const TimeOfDay(hour: 0, minute: 30);
    final morningEnd = const TimeOfDay(hour: 11, minute: 30);

    final afternoonStart = const TimeOfDay(hour: 13, minute: 0);
    final afternoonEnd = const TimeOfDay(hour: 20, minute: 0);

    return (_isTimeOfDayInRange(time, morningStart, morningEnd) ||
        _isTimeOfDayInRange(time, afternoonStart, afternoonEnd));
  }

  // 辅助方法：判断时间是否在范围内
  bool _isTimeOfDayInRange(TimeOfDay time, TimeOfDay start, TimeOfDay end) {
    final now = DateTime.now();
    final startDateTime = DateTime(now.year, now.month, now.day, start.hour, start.minute);
    final endDateTime = DateTime(now.year, now.month, now.day, end.hour, end.minute);
    final currentDateTime = DateTime(now.year, now.month, now.day, time.hour, time.minute);

    return currentDateTime.isAfter(startDateTime) && currentDateTime.isBefore(endDateTime);
  }

  // 刷新可见的股票数据
  void _refreshVisibleStocks() {
    final visibleSymbols = _calculateVisibleSymbols();
    if (visibleSymbols.isNotEmpty) {
      _isRefreshing(true);
      _refreshTrigger.value++;
      controller.refreshVisibleStocks(visibleSymbols.toList()).then((_) {
        _isRefreshing(false);
      });
    }
  }

  // 注册列表项的GlobalKey
  void _registerItemKey(String symbol, GlobalKey key) {
    _itemKeys[symbol] = key;
  }

  // 取消注册列表项的GlobalKey
  void _unregisterItemKey(String symbol) {
    _itemKeys.remove(symbol);
  }

  // 计算可见的股票代码
  Set<String> _calculateVisibleSymbols() {
    final visibleSymbols = <String>{};
    final RenderBox? listViewRenderBox = _listViewKey.currentContext?.findRenderObject() as RenderBox?;
    if (listViewRenderBox == null) return visibleSymbols;

    final listViewOffset = listViewRenderBox.localToGlobal(Offset.zero);
    final listViewHeight = listViewRenderBox.size.height;

    for (final entry in _itemKeys.entries) {
      final GlobalKey itemKey = entry.value;
      final RenderBox? itemRenderBox = itemKey.currentContext?.findRenderObject() as RenderBox?;

      if (itemRenderBox != null) {
        final itemOffset = itemRenderBox.localToGlobal(Offset.zero);
        final itemHeight = itemRenderBox.size.height;

        if (itemOffset.dy + itemHeight >= listViewOffset.dy &&
            itemOffset.dy <= listViewOffset.dy + listViewHeight) {
          visibleSymbols.add(entry.key);
        }
      }
    }

    return visibleSymbols;
  }

  void _navigateToAddBuyRecord() async {
    final result = await Get.toNamed('/addBuyRecord');
    if (result == true) {
      controller.refreshData();
    }
  }

  // 按浮动盈亏比率降序排序持仓列表
  List<ObservableStockPosition> _sortPositionsByProfitRate(List<ObservableStockPosition> positions) {
    return positions.toList()
      ..sort((a, b) {
        // 计算浮动盈亏比率
        final aProfitRate = a.position.averageCost > 0
            ? ((a.currentPrice.value - a.position.averageCost) / a.position.averageCost) * 100
            : 0.0;

        final bProfitRate = b.position.averageCost > 0
            ? ((b.currentPrice.value - b.position.averageCost) / b.position.averageCost) * 100
            : 0.0;

        return bProfitRate.compareTo(aProfitRate); // 降序排列
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Obx(() => Row(
          children: [
            const Text('股票持仓'),
            if (_isRefreshing.value) ...[
              const SizedBox(width: 8),
              const Icon(Icons.autorenew, size: 18, color: Colors.green),
              const SizedBox(width: 4),
              const Text('自动刷新中', style: TextStyle(fontSize: 14)),
            ],
          ],
        )),
        backgroundColor: Colors.blue[700],
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _navigateToAddBuyRecord,
          ),
        ],
      ),
      body: Column(
        children: [
          // 搜索框
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                labelText: '搜索股票代码或名称',
                prefixIcon: const Icon(Icons.search),
                suffixIcon: _searchController.text.isNotEmpty
                    ? IconButton(
                  icon: const Icon(Icons.clear, size: 20),
                  onPressed: _clearSearch,
                )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
              ),
              onChanged: (value) {
                controller.setSearchQuery(value);
              },
            ),
          ),
          // 过滤选项栏
          Container(
            padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 16.0),
            child: Column(
              children: [
                Row(
                  children: [
                    const Text(
                      '盈亏比率过滤:',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextField(
                        controller: _filterController,
                        decoration: InputDecoration(
                          hintText: '输入百分比 (如 3 或 -5)',
                          border: const OutlineInputBorder(),
                          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        ),
                        keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                        onSubmitted: (value) {
                          _applyFilter();
                        },
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '%',
                      style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey[700]),
                    ),
                    const SizedBox(width: 8),
                    ElevatedButton(
                      onPressed: _applyFilter,
                      child: const Text('确认'),
                    ),
                    const SizedBox(width: 4),
                    IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: _clearFilter,
                      tooltip: '重置为默认值',
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Obx(() => Row(
                  children: [
                    Checkbox(
                      value: controller.showClearedStocks.value,
                      onChanged: (value) {
                        controller.setShowClearedStocks(value ?? false);
                      },
                    ),
                    const Text('显示已清仓股票'),
                  ],
                )),
              ],
            ),
          ),
          // 持仓列表
          Expanded(
            child: Obx(() {
              if (controller.isLoading.value) {
                return const Center(child: CircularProgressIndicator());
              }

              // 获取过滤后的持仓并按浮动盈亏比率降序排序
              final allPositions = _sortPositionsByProfitRate(controller.filteredPositions);

              if (allPositions.isEmpty) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.list_alt, size: 64, color: Colors.grey),
                      const SizedBox(height: 16),
                      Text(
                        controller.searchQuery.isEmpty &&
                            controller.filterPercent.value == 3.0 && // Changed to 3.0
                            !controller.showClearedStocks.value
                            ? '暂无持仓记录或盈亏比率≥3%的持仓'
                            : '未找到匹配的持仓',
                        style: const TextStyle(fontSize: 18, color: Colors.grey),
                      ),
                      const SizedBox(height: 20),
                      if (controller.searchQuery.isEmpty &&
                          controller.filterPercent.value == 3.0 && // Changed to 3.0
                          !controller.showClearedStocks.value)
                        ElevatedButton(
                          onPressed: _navigateToAddBuyRecord,
                          child: const Text('添加买入记录'),
                        ),
                    ],
                  ),
                );
              }

              return Obx(() {
                final refreshCount = _refreshTrigger.value;

                return RefreshIndicator(
                  onRefresh: () async {
                    await controller.refreshData();
                  },
                  child: ListView.builder(
                    key: _listViewKey,
                    itemCount: allPositions.length,
                    itemBuilder: (context, index) {
                      final position = allPositions[index];
                      return StockPositionListItem(
                        observablePosition: position,
                        filterPercent: controller.filterPercent.value,
                        refreshTrigger: refreshCount,
                        registerItemKey: _registerItemKey,
                        unregisterItemKey: _unregisterItemKey,
                        key: ValueKey('${position.position.symbol}_${controller.filterPercent.value}'),
                      );
                    },
                  ),
                );
              });
            }),
          ),
        ],
      ),
    );
  }
}